/*
 * CRtpUnPacker.cpp
 *
 *  Created on: 2018年4月21日
 *      Author: zhengboyuan
 */

#include "CRtpUnPacker.h"

namespace av
{

CRtpUnPacker::CRtpUnPacker():
		m_mediaType(),
		m_codec(),
		m_format(),
		m_lastTs()
{
}

CRtpUnPacker::~CRtpUnPacker()
{
}

bool CRtpUnPacker::open(int mediaType, int codec)
{
	m_mediaType = mediaType;
	m_codec = codec;

	if (m_mediaType == MEDIA_TYPE_AUDIO)
	{
		m_format.m_audioCodec = (MediaCodec)codec;
	}
	else
	{
		m_format.m_codec = (MediaCodec)codec;
	}

	return true;
}

bool CRtpUnPacker::unpack(RtpPacket& pktIn, MediaPacket& pktOut)
{
	bool found = false;

	ByteBuffer& buffer = m_buffer.getCurBuffer();
	buffer.write(pktIn.data, pktIn.size);

	bool isComplete = pktIn.mark;
	if (!isComplete)
	{
	    isComplete = (m_lastTs != pktIn.ts);
	}

	if (isComplete)
	{
		pktOut.set_type(m_mediaType);
		pktOut.set_dts(pktIn.ts);
		pktOut.set_duration(0);
		pktOut.copy(buffer.data(), buffer.size());

		m_buffer.switchBuffer();
		m_buffer.getCurBuffer().clear();

		m_lastTs = pktIn.ts;
		found = true;
	}
	return found;
}

void CRtpUnPacker::close()
{
	m_buffer.clear();

	m_lastTs = 0;
}

bool CRtpUnPacker::getFormat(MediaFormat& format)
{
	format = m_format;
	return true;
}




} /* namespace av */
